/*
   @Copyright:LeetCode
   @Author:   tjyemail
   @Problem:  http://leetcode.com/problems/reorder-list
   @Language: C++
   @Datetime: 19-11-19 13:21
   */

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
	void reorderList(ListNode* head) {
		ListNode *p, *q, H(-1);
		for(H.next=head, p=q=&H; p && (p=p->next); p=p->next, q=q->next);
		head=q->next;
		q->next=NULL;
		for(p=NULL; head; swap(head,p))
			swap(p,head->next);
		for(q=H.next, head=&H; p && q;){
			head=head->next=q;
			q=q->next;
			head=head->next=p;
			p=p->next;
		}
		head->next=(p?p:q);
	}
};
